package demo2;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if(this.age - o.age > 0) {
            return 1;
        }else if(this.age - o.age < 0) {
            return -1;
        }else {
            return 0;
        }
        //return 0;
    }
}
//todo: Comparator接口当中 不止一个抽象方法  那么  为什么只需要实现一个compare方法就好了
class AgeComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

public class Test2 {

    public static void main(String[] args) {
        Student student1 = new Student("bit", 10);
        Student student2 = new Student("hello", 40);

        AgeComparator ageComparator = new AgeComparator();

        if (ageComparator.compare(student1, student2) > 0) {
            System.out.println("student1 > student2");
        } else {
            System.out.println("student1 < student2");
        }
    }


    public static void main5(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("bit", 10);
        students[1] = new Student("hello", 40);
        students[2] = new Student("gbc", 5);
        //根据年龄比较
        //AgeComparator ageComparator = new AgeComparator();
        // Arrays.sort(students, AgeComparator);
         //根据名字比较
        NameComparator nameComparator = new NameComparator();
        Arrays.sort(students, nameComparator);

        System.out.println(Arrays.toString(students));
    }
}
